<?php
/**
 * Created by PhpStorm.
 * User: Yangjinlei
 * Date: 2018/7/6
 * Time: 9:47
 */

namespace app\traits;


use app\http\exception\AuthException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;

trait Auth
{
    protected $key;
    /**
     * @var int $exp Token 过期时间
     */
    protected $exp = 7200;

    protected $token = [
        "iss" => "http://api.yyang.xin",
        "aud" => "http://api.yyang.xin",
        "iat" => 0
    ];

    /**
     * @return String 获取私钥内容
     */
    abstract function Key();

    /**
     * @return String 获取公钥内容
     */
    abstract function pubKey();

    public function createToken($uid){
        $this->token['iat'] = time();
        $this->token['exp'] = time()+$this->exp;
        $this->token['user_id'] = $uid;
        $this->key = $this->Key();
        return JWT::encode($this->token,$this->key,'HS256');
    }

    /**
     * @param $token
     * @param string $name
     * @return int $uid
     * @throws AuthException
     */
    public function parseToken($token,$name='admin_'){
        if ($token == '' || $token==null)
            throw new AuthException('请登录');
        $jwt = str_replace('Bearer ','',$token);
        try{
            $data = JWT::decode($jwt, $this->Key(), ['HS256']);
            return $data->user_id;
        }catch (ExpiredException $e){
            $tks = explode('.', $token);
            list($headb64, $bodyb64, $cryptob64) = $tks;
            $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
//            if ($payload->user_id>=1000)
//                cache('user_'.$payload->user_id,null);
//            else
//                cache('admin_'.$payload->user_id,null);
            cache($name.$payload->user_id,null);
            throw new AuthException($e->getMessage());
        }
        catch (\Exception $exception){
            throw new AuthException($exception->getMessage());
        }
    }
}